using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCell.AuthServer.Commands;
using WCell.Core.Addons;

using WCell.Core;
using WCell.Constants;
using WCell.Core.Initialization;
using NLog;
using System.IO;
using WCell.Util.Variables;

namespace WCell.AuthServer.Addons
{
	/// <summary>
	/// Static helper and container class of all kinds of Addons
	/// </summary>
	public static class AddonMgr
	{
		static Logger log = LogManager.GetCurrentClassLogger();

		[Variable("AddonDescriptions")]
		public static string DescriptorString = "";

		public static string AddonDir = "../Lib";
		
		[Initialization(InitializationPass.First, "Initialize Addons")]
		public static void Initialize(InitMgr mgr)
		{
			WCellAddonDescriptor.ParseDefault(AddonDir, DescriptorString);
			//WCellAddonMgr.RegisterResolveHandler();
			// descriptors.LoadAll(true);

			if (WCellAddonMgr.Descriptors.Count > 0)
			{
				log.Info("Found {0} Addon(s):", WCellAddonMgr.Descriptors.Count);
				foreach (var desc in WCellAddonMgr.Descriptors)
				{
					if (!desc.Exists)
					{
						throw new FileNotFoundException("Could not find Addon file: " + desc.FilePath);
					}

					try
					{
						log.Info("Loading Addon from {0}...", desc.FilePath);
						var context = new WCellAddonContext(desc, true);
						log.Info("Loaded: " +
								 (context.Addon != null
									? context.Addon.GetDefaultDescription()
									: (context.Assembly.GetName().Name + " (No Addon initialized)")));

						// register all Commands of the Assembly
						AuthCommandHandler.Instance.AddCmdsOfAsm(context.Assembly);

						// add all initialization steps of the Assembly
						mgr.AddStepsOfAsm(context.Assembly);
					}
					catch (Exception e)
					{
						log.Error("");
						throw new Exception("Failed to load Addon - " + desc, e);
					}
				}
			}
			else
			{
				log.Info("No addons found.");
			}
		}
	}
}
